//
//  ZXOpenMapsSchemeManager.m
//  CAIOpenMapsManager
//
//  Created by zhuxm2023 on 2023/10/25.
//

#import "ZXOpenMapsSchemeManager.h"

@interface ZXOpenMapsSchemeManager ()

@property (nonatomic, strong) NSMutableArray *mapItems;

@end

@implementation ZXOpenMapsSchemeManager

- (void)dealloc{
    
}


- (NSMutableArray *)mapItems
{
    if (!_mapItems) {
        _mapItems = [NSMutableArray array];
    }
    return _mapItems;
}


- (NSArray <NSDictionary*> *)getSupportMapItemSchemes
{
    [self getSupportMapItemSchemesFinishBlock:nil];
    return self.mapItems;
}

- (void)getSupportMapItemSchemesFinishBlock:(nullable void(^)(NSArray <NSDictionary *> *items))finish
{
    [self.mapItems removeAllObjects];
    //判断是否安装高德map
    if ([[UIApplication sharedApplication] canOpenURL:[ZXOpenMapsSchemeManager aMapSchemeURL]]) {
        NSDictionary *amap_dic = @{@"title":@"高德地图",@"mapType":@(ZXMapTypeAMap)};
        [self.mapItems addObject:amap_dic];
    }
    //判断是否安装baidumap
    if ([[UIApplication sharedApplication] canOpenURL:[ZXOpenMapsSchemeManager baiduSchemeURL]]) {
        NSDictionary * dic = @{@"title":@"百度地图",@"mapType":@(ZXMapTypeBaidu)};
        [self.mapItems addObject:dic];
    }
    NSDictionary * dic = @{@"title":@"Apple地图",@"mapType":@(ZXMapTypeApple)};
    [self.mapItems addObject:dic];

    if (finish) {
        finish(self.mapItems);
    }
}

#pragma mark -

///高德地图路线规划
///sourceApplication 第三方调用应用名称。如applicationName 是
///sid 起点PO IID（例如天安门为B000A60DA1 ）否
///slat 起点纬度，经纬度参数同时存在或同时为空，视为有效参数 否
///slon 起点经度，经纬度参数同时存在或同时为空，视为有效参数 否
///sname 起点名称（可为空） 否;起点经纬度参数为空，且起点名称为空，则以“我的位置”发起路线规划。
///did 终点PO IID（例如天安门为B000A60DA1 ）否
///dlat 终点纬度，经纬度参数同时存在或同时为空，视为有效参数 否
///dlon 终点经度，经纬度参数同时存在或同时为空，视为有效参数 否
///dname 终点名称（可为空）否
///dev 起终点是否偏移。0:lat和lon是已经加密后的,不需要国测加密;1:需要国测加密，可为空，但起点或终点不为空时，不能为空。否 即0:WGS－84,1:GCJ－02
///t = 0 驾车；t = 1 公交；t = 2 步行；t = 3 骑行（骑行仅在V788以上版本支持）；
+ (void)openSchemeURLToAMapClientForNavigationWithLatitude:(double)lat
                                                 longitude:(double)lon
                                                   poiName:(nullable NSString *)poiName
                                               openFailure:(void(^)(NSString *tostTitle))failure
{
    BOOL canOpen = [[UIApplication sharedApplication] canOpenURL:[self aMapSchemeURL]];
    if (!canOpen) {
        if (failure) {
            failure(@"请先安装高德地图App哦～");
        }
        return;
    }
    NSString *bundleName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"];
    NSString *stringURL = [NSString stringWithFormat:@"iosamap://path?sourceApplication=%@&sid=&slat=&slon=&sname=&did=&dlat=%f&dlon=%f&dname=%@&dev=0&t=0",bundleName,lat,lon,poiName];
    stringURL = [stringURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    [self openURL:stringURL options:@{} completionHandler:nil];
}


/// BaiduMap路线规划
/// origin:起点名称或经纬度，或者可同时提供名称和经纬度，此时经纬度优先级高，将作为导航依据，名称只负责展示。必选；
/// destination:终点名称或经纬度，或者可同时提供名称和经纬度，此时经纬度优先级高，将作为导航依据，名称只负责展示。必选；
/// name最后传值，不然地图上目的地只会展示“地图上的点”,也看不到建筑物名字，不友好；只是简单的显示指定的位置，不会去执行位置搜索；
/// mode:导航模式，固定为transit、driving、navigation、walking，riding分别表示公交、驾车、导航、步行和骑行.必选；
/// coord_type:坐标类型，虽然默认是baidu的，但可以设置修改其它类型。必选参数。
/// src:表示来源，用于统计.必选.必选参数，格式为：ios.companyName.appName 不传此参数，不保证服务.
+ (void)openSchemeURLToBaiduMapClientForNavigationWithLatitude:(double)lat
                                                     longitude:(double)lon
                                                       poiName:(nullable NSString *)poiName
                                                   openFailure:(nullable void(^)(NSString *tostTitle))failure
{
    BOOL canOpen = [[UIApplication sharedApplication] canOpenURL:[self baiduSchemeURL]];
    if (!canOpen) {
        if (failure) {
            failure(@"请先安装百度地图App哦～");
        }
        return;
    }
    NSString *stringURL =[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name:%@&mode=driving&coord_type=gcj02&src=%@",lat,lon,poiName,[[NSBundle mainBundle]bundleIdentifier]];
    stringURL = [stringURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    [self openURL:stringURL options:@{} completionHandler:nil];
}


/// 获取Apple地图路线，导航方向；
/// sadder: 起点，如果你不指定saddrd的值,起点是"here";非必须；
/// dirflg:指定交通类型;非必须；
/// daddr: 终点，目的地址。如果你没有传终点，则用目的经纬度；
+ (void)openSchemeURLToAppleMapClientForNavigationWithLatitude:(double)lat
                                                     longitude:(double)lon
                                                       poiName:(nullable NSString *)poiName
{
    //如果没有传目的位置名称，则根据目的位置经纬度
    NSString *stringURL;
    if (poiName) {
        stringURL = [NSString stringWithFormat:@"http://maps.apple.com/?daddr=%@&dirflg=d",poiName];
    }else{
        NSString *location = [NSString stringWithFormat:@"%f,%f",lat,lon];
        stringURL = [NSString stringWithFormat:@"http://maps.apple.com/?daddr=%@&dirflg=d",location];
    }
    stringURL = [stringURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    [self openURL:stringURL options:@{} completionHandler:nil];
}


#pragma mark -

+ (NSURL *)aMapSchemeURL{
    NSURL *amapSchemeURL = [NSURL URLWithString:@"iosamap://"];
    return amapSchemeURL;
}

+ (NSURL *)baiduSchemeURL{
    NSURL *uRL = [NSURL URLWithString:@"baidumap://"];
    return uRL;
}

+ (void)openURL:(NSString *)stringURL options:(NSDictionary<UIApplicationOpenExternalURLOptionsKey, id> *)options completionHandler:(void (^ __nullable)(BOOL success))completion{
    
    NSURL *url =[NSURL URLWithString:stringURL];
    if (@available(iOS 10.0,*)) {
        [[UIApplication sharedApplication]openURL:url options:options completionHandler:completion];
    }
    else
    {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        [[UIApplication sharedApplication] openURL:url];
#pragma clang diagnostic pop
    }
}

@end
